SpringBoot 整合 Redis 使用详解

SpringBoot 整合 Redis 使用详解(StringRedisTemplate 和 RedisTemplate 对比分析)

SpringBoot整合redis的详细过程,以及部分源码分析

前期准备

首先保证安装好redis,并开启远程访问权限(最好配置密码)

pom.xml添加依赖:

1
2
3
4
5

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

application.yml:

1
2
3
4
5
6
7
8
9
10
11
12
13

spring:
redis:
database: 0
host: 140.143.23.94
password: 123
port: 6379
timeout: 3000 # 连接超时时间 单位 ms(毫秒)
pool:
max-idle: 8 # 连接池中的最大空闲连接,默认值也是8
min-idle: 0 # 连接池中的最小空闲连接,默认值也是0
max-active: 8 # 如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
max-wait: -1 # 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出

选择合适的API:

这个主要是根据redis存储的数据类型需求决定,key一般都是String,但是value可能不一样,一般有两种,String和 Object;
如果k-v都是String类型,我们可以直接用 StringRedisTemplate,这个是官方建议的,也是最方便的,直接导入即用,无需多余配置!
如果k-v是Object类型,则需要自定义 RedisTemplate,在这里我们都研究下!

StringRedisTemplate

redis封装工具类:(内部导入的是StringRedisTemplate,RedisTemplate也可以)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class IRedisService {
@Autowired
protected StringRedisTemplate redisTemplate;
/**
* 写入redis缓存(不设置expire存活时间)
* @param key
* @param value
* @return
*/
public boolean set(final String key, String value){
boolean result = false;
try {
ValueOperations operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
log.error("写入redis缓存失败!错误信息为:" + e.getMessage());
}
return result;
}
/**
* 写入redis缓存(设置expire存活时间)
* @param key
* @param value
* @param expire
* @return
*/
public boolean set(final String key, String value, Long expire){
boolean result = false;
try {
ValueOperations operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expire, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
log.error("写入redis缓存(设置expire存活时间)失败!错误信息为:" + e.getMessage());
}
return result;
}
/**
* 读取redis缓存
* @param key
* @return
*/
public Object get(final String key){
Object result = null;
try {
ValueOperations operations = redisTemplate.opsForValue();
result = operations.get(key);
} catch (Exception e) {
log.error("读取redis缓存失败!错误信息为:" + e.getMessage());
}
return result;
}
/**
* 判断redis缓存中是否有对应的key
* @param key
* @return
*/
public boolean exists(final String key){
boolean result = false;
try {
result = redisTemplate.hasKey(key);
} catch (Exception e) {
log.error("判断redis缓存中是否有对应的key失败!错误信息为:" + e.getMessage());
}
return result;
}
/**
* redis根据key删除对应的value
* @param key
* @return
*/
public boolean remove(final String key){
boolean result = false;
try {
if(exists(key)){
redisTemplate.delete(key);
}
result = true;
} catch (Exception e) {
log.error("redis根据key删除对应的value失败!错误信息为:" + e.getMessage());
}
return result;
}
/**
* redis根据keys批量删除对应的value
* @param keys
* @return
*/
public void remove(final String... keys){
for(String key : keys){
remove(key);
}
}
}

使用:(@Autowired导入即可使用)

1
2
3
4
5
6

@Autowired
IRedisService iRedisService;

//将session信息存入redis,设置存活时间为30分钟
iRedisService.set(sessionid, sessionJson, 30*60L;

RedisTemplate

在此存入redis的类型为:String:Object

1
2
3
4
5
6
7
8

RedisTemplate中定义了对5种数据结构操作:

redisTemplate.opsForValue();//操作字符串
redisTemplate.opsForHash();//操作hash
redisTemplate.opsForList();//操作list
redisTemplate.opsForSet();//操作set
redisTemplate.opsForZSet();//操作有序set

自定义Redis序列化工具类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

public class RedisObjectSerializer implements RedisSerializer<Object> {

static final byte[] EMPTY_ARRAY = new byte[0];

@Override
public Object deserialize(byte[] bytes) {
if (isEmpty(bytes)) {
return null;
}
ObjectInputStream oii = null;
ByteArrayInputStream bis = null;
bis = new ByteArrayInputStream(bytes);
try {
oii = new ObjectInputStream(bis);
Object obj = oii.readObject();
return obj;
} catch (Exception e) {

e.printStackTrace();
}
return null;
}

@Override
public byte[] serialize(Object object) {
if (object == null) {
return EMPTY_ARRAY;
}
ObjectOutputStream obi = null;
ByteArrayOutputStream bai = null;
try {
bai = new ByteArrayOutputStream();
obi = new ObjectOutputStream(bai);
obi.writeObject(object);
byte[] byt = bai.toByteArray();
return byt;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

private boolean isEmpty(byte[] data) {
return (data == null || data.length == 0);
}
}

Redis配置类:

网上大多数都是配置Jackson2JsonRedisSerializer序列化类,这里用自定义的序列化类!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

@Configuration
public class RedisConfig {

@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)
{
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
RedisObjectSerializer redisObjectSerializer = new RedisObjectSerializer();

RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(redisConnectionFactory);
template.setKeySerializer(stringRedisSerializer);
template.setValueSerializer(redisObjectSerializer);
return template;
}
}

定义测试User实体类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
public class User implements Serializable{

private static final long serialVersionUID = -8289770787953160443L;

public User(Integer userId, String userName, String password, String phone) {
this.userId = userId;
this.userName = userName;
this.password = password;
this.phone = phone;
}

private Integer userId;
private String userName;
private String password;
private String phone;


public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}

@Override
public String toString() {
return "User{" +
"userId=" + userId +
", userName='" + userName + '\'' +
", password='" + password + '\'' +
", phone='" + phone + '\'' +
'}';
}
}

使用测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

@RunWith(SpringRunner.class)
@SpringBootTest
public class YjApplicationTests {

@Autowired
private IRedisService iRedisService;

@Autowired
private RedisTemplate<String, Object> redisTemplate;


@Test
public void testRedis(){
// iRedisService.set("aaa","BBB");
redisTemplate.opsForValue().set("user1",new User(1,"yj","123","111"));
User user1 = (User)redisTemplate.opsForValue().get("user1");
System.out.println(user1);
}
}

StringRedisTemplate 和 RedisTemplate 对比分析

区别和联系

第一点,StringRedisTemplate继承了RedisTemplate。

第二点,RedisTemplate是一个泛型类,而StringRedisTemplate则不是。

第三点,StringRedisTemplate只能对key=String,value=String的键值对进行操作,RedisTemplate可以对任何类型的key-value键值对操作。

第四点,是他们各自序列化的方式不同,但最终都是得到了一个字节数组,殊途同归,StringRedisTemplate使用的是StringRedisSerializer类;RedisTemplate使用的是JdkSerializationRedisSerializer类。反序列化,则是一个得到String,一个得到Object

源码分析

先看 StringRedisTemplate:

1
2
3
4
5
6
7
8
9
10
11
12
13
14

public class StringRedisTemplate extends RedisTemplate<String, String> {

/**
* Constructs a new <code>StringRedisTemplate</code> instance. {@link #setConnectionFactory(RedisConnectionFactory)}
* and {@link #afterPropertiesSet()} still need to be called.
*/
public StringRedisTemplate() {
RedisSerializer<String> stringSerializer = new StringRedisSerializer();
setKeySerializer(stringSerializer);
setValueSerializer(stringSerializer);
setHashKeySerializer(stringSerializer);
setHashValueSerializer(stringSerializer);
}

StringRedisTemplate 是继承 RedisTemplate的,一般来说子类继承父类,应该能实现更多的功能,但是此处我们发现 StringRedisTemplate 继承的是 RedisTemplate的泛型类,指定了String-String的泛型!故功能只专注于String类型!

其次我们可以看到 StringRedisTemplate 的构造方法中指定了序列化类为 StringRedisSerializer,我们进去看看:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

public class StringRedisSerializer implements RedisSerializer<String> {

private final Charset charset;

public StringRedisSerializer() {
this(Charset.forName("UTF8"));
}

public StringRedisSerializer(Charset charset) {
Assert.notNull(charset, "Charset must not be null!");
this.charset = charset;
}

public String deserialize(byte[] bytes) {
return (bytes == null ? null : new String(bytes, charset));
}

public byte[] serialize(String string) {
return (string == null ? null : string.getBytes(charset));
}
}

这下就一目了然了!

再看 RedisTemplate:

1
2
3
4
5
6
7
8
9
10
11
12
13

public void afterPropertiesSet() {

super.afterPropertiesSet();

boolean defaultUsed = false;

if (defaultSerializer == null) {

defaultSerializer = new JdkSerializationRedisSerializer(
classLoader != null ? classLoader : this.getClass().getClassLoader());
}
}

可以看到默认序列化方式为 JdkSerializationRedisSerializer:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

public class JdkSerializationRedisSerializer implements RedisSerializer<Object> {

private final Converter<Object, byte[]> serializer;
private final Converter<byte[], Object> deserializer;

/**
* Creates a new {@link JdkSerializationRedisSerializer} using a {@link Converter converters} to serialize and
* deserialize objects.
*
* @param serializer must not be {@literal null}
* @param deserializer must not be {@literal null}
* @since 1.7
*/
public JdkSerializationRedisSerializer(Converter<Object, byte[]> serializer, Converter<byte[], Object> deserializer) {

Assert.notNull(serializer, "Serializer must not be null!");
Assert.notNull(deserializer, "Deserializer must not be null!");

this.serializer = serializer;
this.deserializer = deserializer;
}
}

而JdkSerializationRedisSerializer又调用了SerializingConverter类的convert方法。在这个方法里其转换主要有三步:

1、ByteArrayOutputStream(1024),创建一个字节数组输出流缓冲区。

2、DefaultSerializer.serialize(source, byteStream):把要序列化的数据存储到缓冲区。还想看他是怎么放到缓冲区的,但是,能力有限,水平一般,serialize的细节,实在无能为力,看了半天,还是氐惆。

3、toByteArray:就是把上一步放到缓冲区的数据拷贝到新建的字节数组里。

至此Object的序列化就结束了,返回了一个字节数组。


来源:CSDN
原文链接:https://blog.csdn.net/Abysscarry/article/details/80557347

0%